// @flow
import React, { Component } from 'react'
import styles from './Devices.css'
// import AgGrid from 'components/AgGrid'
import DeviceGrid from './DeviceGrid'
import moment from 'moment'
import LinkToDeviceOverView from './LinkToDeviceOverView'
import DeviceActions from './DeviceActions'
import { saveDeviceData } from 'store/modules/deviceCard'
import { connect } from 'react-redux'
import BusinessFillter from 'components/BusinessFillter'
import universalFetch, { handleFetchError } from 'store/modules/fetch'
import { Button, message } from 'antd'

type Props = {
  userId: string,
  history: Object,
  saveDeviceData: Function
}
type States = {
  columnDefs: Array<Object>,
  rowData: Object,
  current: number,
  total: number,
}
class Devices extends Component {
  props: Props
  state: States
  searchQuery: string
  goToDeviceOverView: Function
  getData: Function
  constructor (props: Props) {
    super(props)
    const component = this
    this.state = {
      rowData: {},
      current: 1,
      total: 1,
      columnDefs: [
        {
          headerName: '设备编号',
          cellRenderer: 'group',
          cellRendererParams: {
            innerRenderer:  (params) => {
              return params.data.deviceNo
            }
          },
          field: 'deviceNo',
          width: 200,
          cellStyle: {
            padding: '8px'
          }
        },
        {
          headerName: '设备名称',
          width: 200,
          field: 'name',
          cellStyle: {
            padding: '8px'
          },
          cellRendererParams: {
            goToDeviceOverView: component.goToDeviceOverView.bind(this)
          },
          cellRendererFramework: LinkToDeviceOverView
        },
        {
          headerName: '设备类型',
          field: 'type',
          width: 150,
          cellStyle: {
            padding: '8px'
          }
        },
        {
          headerName: '设备型号',
          field: 'spec',
          width: 150,
          cellStyle: {
            padding: '8px'
          }
        },
        {
          headerName: '负责人',
          field: 'owner',
          width: 150,
          cellStyle: {
            padding: '8px'
          }
        },
        // {
        //   headerName: '数据源',
        //   field: 'dataSource',
        //   width: 100,
        //   cellStyle: {
        //     padding: '8px',
        //     'text-align': 'center'
        //   }
        // },
        {
          headerName: '设备状态',
          field: 'status',
          width: 150,
          cellStyle: {
            padding: '8px'
          }
        },
        {
          headerName: '客户名称',
          field: 'customer.name',
          width: 200,
          cellStyle: {
            padding: '8px'
          }
        },
        {
          headerName: '投运日期',
          field: 'operationDate',
          width: 150,
          cellStyle: {
            padding: '8px',
            'text-align': 'center'
          }
          // cellRenderer: (params) => {
          //   const operationDate = params.data.operationDate
          //   if (operationDate) {
          //     return moment(params.data.operationDate, 'YYYY-MM-DDTHH:mm:ss.SSSZ').format('YYYY-MM-DD')
          //   } else {
          //     return ''
          //   }
          // }
        },
        {
          headerName: '生产日期',
          field: 'produceDate',
          width: 150,
          cellStyle: {
            padding: '8px',
            'text-align': 'center'
          }
          // cellRenderer: (params) => {
          //   const produceDate = params.data.produceDate
          //   if (produceDate) {
          //     return moment(params.data.produceDate, 'YYYY-MM-DDTHH:mm:ss.SSSZ').format('YYYY-MM-DD')
          //   } else {
          //     return ''
          //   }
          // }
        },
        {
          headerName: '操作',
          minWidth: 250,
          maxWidth: 250,
          suppressFilter: true,
          cellStyle: {
            padding: '6px 8px',
            'text-align': 'left'
          },
          cellRendererParams: {
            history: this.props.history,
            deletPart: this.deletPart,
            addPart: this.addPart,
            editPart: this.editPart
          },
          cellRendererFramework: DeviceActions
        }
      ]
    }

    this.goToDeviceOverView = this.goToDeviceOverView.bind(this)
    this.getData = this.getData.bind(this)
  }
  componentDidMount () {
    this.getData()
  }
  goToDeviceOverView (data: Object) {
    const { history, saveDeviceData } = this.props
    saveDeviceData(data)
    history.push(`/device-file/${data.id}/overview`)
  }
  getData (page: number = 1, pageSize: number = 20, searchQuery: string = '') {
    let API
    if (searchQuery) {
      this.searchQuery = searchQuery
    }
    const searchQuerys = this.searchQuery || ''
    const state = history.state
    if (state) {
      if (state.hasOwnProperty('state')) {
        if (state.state) {
          // 从客户列表跳转过来（查询改客户下的所有设备）
          const { customerId } = history.state.state
          API = `${__SERVICE_API__}device/customers/${customerId}/devices?withBoms=true`
          universalFetch(API)
            .then(res => res.json())
            .then((json) => {
              if (json.code !== 200000) {
                throw new Error(JSON.stringify({ code: json.code, message: json.message }))
              }
              this.setState({
                rowData: json.result.map((d, i) => {
                  const operationDate = d.operationDate
                  if (operationDate) {
                    d['operationDate'] = moment(d.operationDate, 'YYYY-MM-DDTHH:mm:ss.SSSZ').format('YYYY-MM-DD')
                  } else {
                    d['operationDate'] = ''
                  }
                  const produceDate = d.produceDate
                  if (produceDate) {
                    d['produceDate'] = moment(d.produceDate, 'YYYY-MM-DDTHH:mm:ss.SSSZ').format('YYYY-MM-DD')
                  } else {
                    d['produceDate'] = ''
                  }
                  return d
                })
              })
            })
            .catch((error) => {
              handleFetchError(error)
              console.error(error)
            })
          return
        }
      }
    }
    // 查询所有设备
    API = `${__SERVICE_API__}device/devices?userId=${this.props.userId}&pageNum=${page}&pageSize=${pageSize}&withBoms=true&orderBy=update_time desc${searchQuerys}`
    universalFetch(API)
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        this.setState({
          current: page,
          total: json.pageInfo.total,
          rowData: json.result.map((d, i) => {
            const operationDate = d.operationDate
            if (operationDate) {
              d['operationDate'] = moment(d.operationDate, 'YYYY-MM-DDTHH:mm:ss.SSSZ').format('YYYY-MM-DD')
            } else {
              d['operationDate'] = ''
            }
            const produceDate = d.produceDate
            if (produceDate) {
              d['produceDate'] = moment(d.produceDate, 'YYYY-MM-DDTHH:mm:ss.SSSZ').format('YYYY-MM-DD')
            } else {
              d['produceDate'] = ''
            }
            return d
          })
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }
  deletPart = (data) => {
    universalFetch(`${__SERVICE_API__}device/devices/${data.id}`, {
      method: 'DELETE'
    })
    .then((res) => res.json())
    .then((json) => {
      if (json.code !== 200000) {
        throw new Error(JSON.stringify({ code: json.code, message: json.message }))
      }
      message.success('删除成功')
      this.getData()
    })
     .catch((error) => {
       handleFetchError(error)
       console.error(error)
       message.error('删除失败')
     })
  }
  addPart = (values) => {
    universalFetch(`${__SERVICE_API__}device/devices`, {
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      method: 'POST',
      body: JSON.stringify(values)
    })
    .then((res) => res.json())
    .then((json) => {
      if (json.code !== 200000) {
        throw new Error(JSON.stringify({ code: json.code, message: json.message }))
      }
      message.success('部件添加成功')
      this.getData()
    })
    .catch((error) => {
      handleFetchError(error)
      console.error(error)
      message.error('部件添加失败： ' + error.message)
    })
  }
  editPart = (data, values) => {
    universalFetch(`${__SERVICE_API__}device/devices/${data.id}`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      },
      body: JSON.stringify(values)
    })
    .then((res) => res.json())
    .then((json) => {
      if (json.code !== 200000) {
        throw new Error(JSON.stringify({ code: json.code, message: json.message }))
      }
      message.success('部件修改成功')
      this.getData()
    })
    .catch((error) => {
      handleFetchError(error)
      console.error(error)
      message.error('部件修改失败： ' + error.message)
    })
  }
  render () {
    const { columnDefs, rowData, current, total } = this.state
    const { history } = this.props
    return (
      <div className={styles['main']}>
        <div className={styles['fillterMenu']}>
          <div className={styles['mainBar']}>
            <Button type='primary' className={styles['addBtn']}
              onClick={() => history.push('/business/device-add')}>添加设备</Button>
          </div>
          <BusinessFillter getData={this.getData} />
        </div>
        <DeviceGrid {...{
          columnDefs,
          pageSize: 20
        }}
          rowData={rowData}
          current={current}
          total={total}
          getData={this.getData}
          />
      </div>
    )
  }
}

const mapStatesToProps = (state) => {
  return {
    userId: state.user.userId
  }
}

export default connect(mapStatesToProps, { saveDeviceData })(Devices)
